<!-- 基础信息 -->
<template>
    <div class="outer ">
        <el-form ref="form" :model="form" label-width="7.29vw">
            <div class="select">
                <el-form-item label="发文方式:">
                    <div class="types">
                        <div :class="{ type: true, active: type == 1 }" @click="getType(1)">
                            <i class="el-icon-picture"></i>
                            <span>图文编辑</span>
                            <img v-if="type == 1" class="rIcon" src="@/assets/img/01.png" alt="">
                        </div>
                        <div :class="{ type: true, active: type == 2 }" @click="getType(2)">
                            <i class="iconfont">&#xe8df;</i>
                            <span>文件上传</span>
                            <img v-if="type == 2" class="rIcon" src="@/assets/img/01.png" alt="">
                        </div>
                        <div :class="{ type: true, active: type == 3 }" class="type" @click="getType(3)">
                            <i class="iconfont">&#xe691;</i>
                            <span>批量导入</span>
                            <img v-if="type == 3" class="rIcon" src="@/assets/img/01.png" alt="">
                        </div>
                        <div :class="{ type: true, active: type == 4 }" class="type" @click="getType(4)">
                            <i class="iconfont">&#xe8df;</i>
                            <span>内容链接</span>
                            <img v-if="type == 4" class="rIcon" src="@/assets/img/01.png" alt="">
                        </div>
                    </div>
                </el-form-item>
            </div>

            <el-form-item label="目录标题:" required v-if="type != 3 || type == 4">
                <el-input v-model="form.title" placeholder="请输入目录标题"></el-input>
            </el-form-item>

            <el-form-item label="内容链接:" required v-if="type == 4">
                <el-input v-model="form.link" placeholder="请输入站内链接"></el-input>
            </el-form-item>
            <div class="select">
                <el-form-item label="发文专栏:" required>
                    <el-select filterable v-model="form.col_id" placeholder="请选择专栏" :popper-append-to-body="false">
                        <el-option v-for="item in cols" :key="item.id" :label="item.title" :value="item.id"></el-option>
                    </el-select>
                    <el-option disabled class="load-more" v-if="showMore1">
                        <span @click="loadc">加载更多...</span>
                    </el-option>
                </el-form-item>
            </div>
            <div class="select" v-show="type == 1">
                <el-form-item>
                    <div  class="edit">
                        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig"
                            :mode="mode" />
                        <Editor style="height:500px; overflow-y: hidden;" v-model="html" :defaultConfig="editorConfig"
                            :mode="mode" @onCreated="onCreated" />
                    </div>
                </el-form-item>
            </div>

            <div class="select" v-show="type == 2 || type == 3">
                <el-form-item :label="text" required>
                    <div class="upload">
                        <label v-show="type == 2">
                            <input type="file" @change="onUpload_file">
                            <img src="@/assets/img/icon17.png" alt="">
                            <div style="display: flex;align-items: center;">
                                <!-- <img  style="width: 20px;height: 20px;margin-right: 10px;margin-bottom: 0;" src="@/assets/img/text.png" alt=""> -->
                                <span v-if="filename" style="font-size: 16px;color: #808080;line-height: 20px;">{{
                                    filename }}(点击上传)</span>
                            </div>
                            <p>文件上传【仅支持 mp3,mp4 音视频】</p>
                        </label>
                        <label v-show="type == 3">
                            <input type="file" accept="text/*" @change="onUpload_file">
                            <img src="@/assets/img/icon17.png" alt="">
                            <div style="display: flex;align-items: center;">
                                <!-- <img  style="width: 20px;height: 20px;margin-right: 10px;margin-bottom: 0;" src="@/assets/img/text.png" alt=""> -->
                                <span v-if="filename" style="font-size: 16px;color: #808080;line-height: 20px;">{{
                                    filename }}(点击上传)</span>
                            </div>
                            <p>批量导入</p>
                            <el-button type="primary" @click="download">下载导入模板</el-button>

                        </label>
                    </div>
                </el-form-item>
            </div>


            <el-form-item>
                <div class="btns">
                    <el-button type="primary" @click="onSubmit">提交</el-button>
                </div>
            </el-form-item>
        </el-form>
    </div>
</template>
<script>
import { baseUrl } from '@/apis/index'
import axios from 'axios';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
export default {
    components: { Editor, Toolbar },
    data() {
        return {
            filename: '',
            txt: '',
            url: '',
            form: {
                title: '',
                col_id: [],
                content: ''
            },
            type: 1,
            editor: null,
            html: '',
            toolbarConfig: {
                excludeKeys: [
                    'insertLink',
                    'group-video',
                    'fullScreen'
                ]
            },
            editorConfig: {

            },
            mode: 'default', // or 'simple'
            cols: [],
            id: '',
            info: {},
            text: '',


            totalPagec: 1,
            pageNumc: 1,
            loadingc: false,
            showMore1: false
        }
    },

    created() {
        this.getCols()

        this.editorConfig = {
            MENU_CONF: {
                uploadImage: {
                    server: baseUrl + "user/Upload/one",
                    headers: {
                        'xx-token': localStorage.getItem('token'),
                        'xx-device-type': 'web'
                    },
                    fieldName: 'file',
                    onBeforeUpload(file) {
                        console.log(file);

                        return file


                    },
                    onSuccess(file, res) {          // JS 语法
                        console.log(`${file.name} 上传成功`, res)
                    },
                    customInsert(res, insertFn) {
                        insertFn(res.data.url)
                    }
                },
            }
        }
    },
    mounted() {


        let cid = parseInt(this.$route.query.cid)
        if (cid) {
            this.form.col_id = cid
        }


        let id = parseInt(this.$route.query.id)
        if (id) {
            this.id = id
            this.getChapter()
        }



    },

    methods: {

        loadc() {
            var page = this.pageNumc
            //如果请求未结束就返回不连续请求
            if (this.loadingc) {
                return
            }
            //数据请求完成无更多数据时
            if (page >= this.totalPagec) {
                return false;
            }
            page = parseInt(page) + 1
            this.pageNumc = page
            this.getCols()
        },
        // 获取目录详情
        getChapter() {
            let params = {
                id: this.id
            }
            this.$api.getChapterInfo(params).then(res => {
                if (res.data.code == 1) {
                    let response = res.data.data
                    this.form.title = response.info.title
                    this.form.col_id = response.info.col_id
                    this.form.content = response.info.old_content
                    this.html = response.info.old_content
                    this.type = response.info.op
                    this.form.link = response.info.link
                }
            })
        },
        // 下载导入示例
        download() {
            let url = baseUrl + 'home/base/download'
            window.open(url);
        },

        // 绑定专栏列表
        getCols() {
            this.loadingc = true

            let params = {
                page: this.pageNumc,
                is_zw: 1
            }
            this.$api.getCols(params).then(res => {
                if (res.data.code == 1) {
                    let response = res.data.data
                    this.totalPagec = response.last_page
                    if (this.totalPagec <= this.pageNumc) {
                        this.showMore1 = false
                    } else {
                        this.showMore1 = true
                    }
                    this.cols = this.cols.concat(response.data)
                    this.loadingc = false

                    // this.cols = res.data.data
                }
            })
        },

        // 绑定专栏列表
        // getCols() {
        //     let params = {
        //         is_zw: 1
        //     }

        //     this.$api.getCols(params).then(res => {
        //         if (res.data.code == 1) {
        //             this.cols = res.data.data
        //         }
        //     })
        // },

        onCreated(editor) {
            this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
            console.log(editor.getAllMenuKeys());


            // const curToolbarConfig = toolbar.getConfig()
            console.log(toolbar) // 当前菜单排序和分组

        },
        //批量导入 / 文件上传
        onUpload_file: function (e) {
            console.log(e, '上传的文件是')
            var that = this;
            var file = e.target.files[0];


            // var fileExt = file.name.split('.').pop().toLowerCase();

            // // 检查文件类型
            // if (fileExt !== 'mp4' && fileExt !== 'mp3' && fileExt !== 'txt') {
            //     that.$message({
            //         message: '只允许上传MP3或MP4文件',
            //         type: 'error'
            //     });
            //     return false;
            // }

            var formdata = new FormData();
            formdata.append("file", file, file.name) //通过append向form对象添加
            let config = {
                headers: {
                    "Content-Type": "multipart/form-data",
                    'xx-token': localStorage.getItem('token'),
                    'xx-device-type': 'web'
                }
            }
            axios.post(baseUrl + "user/upload/file", formdata, config).then(function (res) {
                that.$message({
                    message: res.data.msg
                })
                that.filename = res.data.data.filename
                that.url = res.data.data.filepath
                that.txt = res.data.data.url
            }).catch(function (error) {
                that.$message({
                    message: '请求异常'
                })
                console.log("error", error);
                return false;
            })
        },
        getType(i) {
            this.type = i
            this.url = ''
            this.filename = ''
            this.txt = ''

            if (i == 2) {
                this.text = '上传文件:'
            }


            if (i == 3) {
                this.text = '批量导入:'
            }
        },
        handleAvatarSuccess(res, file) {
            console.log(file.raw);
            this.form.imageUrl = URL.createObjectURL(file.raw);
        },

        onSubmit() {
            this.form.content = this.html
            this.form.op = this.type
            this.form.is_fabu = 1
            this.form.cid = this.id
            // 导入
            if (this.type == 3) {
                this.form.url = this.txt
            } else {
                this.form.url = this.url
            }

            let params = this.form

            this.$api.addNewChapter(params).then(res => {
                if (res.data.code == 1) {
                    let id = res.data.data
                    this.$message({
                        message: res.data.msg,
                        type: 'success'
                    })
                    // this.form.title = ''
                    // this.form.col_id = []
                    // this.html = ''
                    // this.url = ''
                    // this.filename = ''
                    // this.txt = ''
                    // this.form.link = ''

                    let old_id = this.id
                    if (old_id) {
                        // 提交后返回上一级
                        this.$router.back()
                    } else {
                        // 添加跳转知识仓目录
                        this.$router.push({
                            path: '/column/list',
                            query: {
                                id: this.form.col_id
                            }
                        })
                    }
                }
            })
        }
    },
    beforeDestroy() {
        const editor = this.editor
        if (editor == null) return
        editor.destroy() // 组件销毁时，及时销毁编辑器
    },
}
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style lang="scss" scoped>
.outer {
    height: 100%;
    overflow-y: auto;
    -ms-overflow-style: none;

    &::-webkit-scrollbar {
        /*滚动条整体样式*/
        width: 0 !important;
        /*高宽分别对应横竖滚动条的尺寸*/
        height: 0 !important;
    }
}

.types {
    display: flex;

    i {
        font-size: 32px;
        margin-right: 0.73rem;
    }
}

.type {
    cursor: pointer;
    width: 8.8rem;
    height: 3.18rem;
    margin-right: 1.35rem;
    background: #FFFFFF;
    border-radius: 0.31rem;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 400;
    font-size: 1.04rem;
    color: #000000;
    border: 1px solid #ccc;

    .tIcon {
        height: 1.46rem;
        width: auto;
        margin-right: 0.73rem;
    }

    .rIcon {
        position: absolute;
        right: 0;
        top: 0;
        width: 1.3rem;
        height: 1.25rem;
    }
}

.active {
    color: #1068E7;
    border: 1px solid #1068E7;

    i {
        color: #1068E7;
    }

}

.upload {
    display: flex;

    label {
        margin-right: 3rem;
        text-align: center;
        white-space: nowrap;
        cursor: pointer;
        font-size: 1rem;
        color: #1a1a1a;

        input[type=file] {

            display: none;
            opacity: 0;
        }

        img {
            display: block;
            margin: 0 auto 0.8rem;
        }
    }
}
.edit{
    border: 1px solid #ccc;width: 1100px
}
</style>